import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const SUCCESS_CODE = 0
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(

  response => {
    const res = response.data
    if (res.code !== SUCCESS_CODE) {
      if (!res instanceof Blob) {
        Message.error(res.message)
      }
    }
    return res
  },
  error => {
    const status = error.response.status
    switch (status) {
      case 403: Message.error('没有足够的权限')
        break
      case 500: Message.error('服务器内部错误')
        break
      default: Message.error('未知的错误')
    }
    return Promise.reject(error)
  }
)

export default service
